<template>
  <div>
    <Button type="primary" style="margin-bottom: 20px" @click="handleAdd"
      >新增食物</Button
    >
    <Table
      :columns="columns"
      :data-source="petFoodList"
      :rowKey="(record) => record.id"
      bordered
    >
      <span slot="ingredients" slot-scope="ingredients">
        <a-tag v-for="(i, index) in ingredients" :key="index">
          {{ ingredientsOptions[i - 1].name }}
        </a-tag>
      </span>
      <span slot="action" slot-scope="text, record">
        <a style="margin-right: 12px" @click="handleEdit(record)">编辑</a>
        <Popconfirm
          title="确定删除该项？"
          ok-text="确定"
          cancel-text="取消"
          @confirm.stop="handleDel(record.id)"
        >
          <a class="text_red"> 删除 </a>
        </Popconfirm>
      </span>
    </Table>
    <Modal
      title="管理食物"
      maskClosable
      :confirm-loading="confirmLoading"
      :visible="openModal"
      :width="700"
      @ok="handleOk"
      @cancel="openModal = false"
    >
      <FoodForm
        :form="foodForm"
        @setFoodForm="setFoodForm"
        :applyOptions="applyOptions"
      />
    </Modal>
  </div>
</template>

<script>
import { Button, Modal, Table, Popconfirm, message } from "ant-design-vue";
import { v4 as uuidv4 } from "uuid";
import FoodForm from "./Modules/foodForm.vue";
import { sleep } from "../../utils/util";
import { findIndex, map } from "lodash";
import {
  typeOptions,
  ingredientsOptions,
  useOptions,
  tasteOptions,
  packagesOptions,
} from "./Modules/const";
const initForm = {
  type: "",
  brand: "",
  ingredients: [],
  use: "",
  taste: "",
  apply: "",
  packages: "",
  residue: null,
};
export default {
  name: "FoodManage",
  components: { Button, Modal, Table, Popconfirm, FoodForm },
  data() {
    return {
      petFoodList: JSON.parse(localStorage.getItem("petFoodList")) || [],
      columns,
      foodForm: initForm,
      openModal: false,
      confirmLoading: false,
      ingredientsOptions,
      applyOptions:
        map(
          JSON.parse(localStorage.getItem("petCategoryList")),
          ({ title }, index) => ({
            value: 1 + index,
            name: title,
          })
        ) || [],
    };
  },
  methods: {
    handleAdd() {
      this.foodForm = initForm;
      this.applyOptions =
        map(
          JSON.parse(localStorage.getItem("petCategoryList")),
          ({ title }, index) => ({
            value: 1 + index,
            name: title,
          })
        ) || [];
      this.openModal = true;
    },
    handleEdit(item) {
      this.openModal = true;
      this.foodForm = item;
    },
    handleDel(id) {
      const index = findIndex(this.petFoodList, (l) => l.id === id);
      this.petFoodList.splice(index, 1);
      this.updateLo();
    },
    async handleOk() {
      this.confirmLoading = true;
      try {
        this.verification();
        const { id } = this.foodForm;
        await sleep(800);
        const data = {
          id: uuidv4(),
          updateTime: new Date().toLocaleString(),
          ...this.foodForm,
        };
        if (id) {
          const index = findIndex(this.petFoodList, (l) => l.id === id);
          this.petFoodList[index] = data;
        } else {
          this.petFoodList.unshift(data);
        }
        message.success("新增成功");
        this.updateLo();
        this.openModal = false;
      } finally {
        this.confirmLoading = false;
      }
    },
    setFoodForm({ type, value }) {
      this.foodForm[type] = value;
    },
    verification() {
      const { type, brand, ingredients, use, taste, apply, packages, residue } =
        this.foodForm;
      console.log("this.foodForm", this.foodForm);
      if (
        !type ||
        !brand ||
        !ingredients?.length ||
        !use ||
        !taste ||
        !apply ||
        !packages ||
        !residue
      ) {
        message.error("请填写完整信息");
        throw new Error("请填写完整信息");
      }
    },
    updateLo() {
      localStorage.setItem("petFoodList", JSON.stringify(this.petFoodList));
    },
  },
};
const columns = [
  {
    title: "食物类型",
    dataIndex: "type",
    align: "center",
    customRender: (text) => typeOptions[text - 1].name,
  },
  {
    title: "食物品牌",
    dataIndex: "brand",
    align: "center",
  },
  {
    title: "食物成分",
    dataIndex: "ingredients",
    align: "center",
    scopedSlots: { customRender: "ingredients" },
  },
  {
    title: "食物用途",
    dataIndex: "use",
    align: "center",
    customRender: (text) => useOptions[text - 1].name,
  },
  {
    title: "食物口味/种类",
    dataIndex: "taste",
    align: "center",
    customRender: (text) => tasteOptions[text - 1].name,
  },
  {
    title: "食物适用对象",
    dataIndex: "apply",
    align: "center",
    customRender: (text) =>
      (map(
        JSON.parse(localStorage.getItem("petCategoryList")),
        ({ title }, index) => ({
          value: 1 + index,
          name: title,
        })
      ) || [])[text - 1].name,
  },
  {
    title: "食物包装规格",
    dataIndex: "packages",
    align: "center",
    customRender: (text) => packagesOptions[text - 1].name,
  },
  {
    title: "数量",
    dataIndex: "residue",
    align: "center",
  },
  {
    title: "更新时间",
    dataIndex: "updateTime",
    align: "center",
  },
  {
    title: "操作",
    scopedSlots: { customRender: "action" },
    width: 160,
    align: "center",
  },
];
</script>
<style lang="less" scoped>
.text_red {
  color: #ed6f6f !important;
}
</style>
